package cn.gjculture.shopping.api.controller;

import cn.gjculture.shopping.api.entity.Return;
import cn.gjculture.shopping.api.entity.FileEntity;
import cn.gjculture.shopping.api.service.FileService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.List;

@Slf4j
@RestController
@RequestMapping(value = "/image")
public class ImageController {

    @Autowired
    FileService fileService;

    @ApiOperation(value="上传图片", notes="上传图片")
    @ApiImplicitParam(name = "type", value = "图片类型，有'icon','goods','hotel'", required = true, dataType = "String", paramType = "path")
    @PostMapping(value = "/upload/{type}")
    public Return upload(@RequestParam("file") MultipartFile file, @PathVariable("type") String type) {
        Return<FileEntity> ret = new Return<>();
        //   List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("fileName");
        List<String> typesList = Arrays.asList(new String[]{"icon", "goods", "hotel","thumb"});
        if (type != null && !typesList.contains(type)) {
            return ret;
        }
        if (file.isEmpty()) {
            return ret;
        }

        String fileName = file.getOriginalFilename();
        log.info("image upload the fileName is {}", fileName);
        int size = (int) file.getSize();
        log.info("image upload the file size is {}", size);
        if (file.isEmpty()) {
            return ret;
        } else {
            FileEntity fileEntity = fileService.saveFile(file, type);
            if (fileEntity != null) {
                ret.setData(fileEntity);
                ret.getCommon().setRet(true);
                return ret;
            }
        }
        return ret;
    }

    @ApiOperation(value="删除图片", notes="根据文件ID删除图片")
    @ApiImplicitParam(name = "fileId", value = "文件ID", required = true, dataType = "String", paramType = "path")
    @DeleteMapping(value ="/{fileId}" )
    public Return upload(@PathVariable("fileId") String fileId){
        Return<String> ret=new Return<>();
        if(fileService.delFile(fileId)){
            ret.getCommon().setRet(true);
        }
        return ret;
    }


}
